import {
  text,
  getPromotion,
  cilckRecord,
  listActivities
} from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    attentions: [],
    mainAct: [],
    acts: [],
    images: [],
    loading: true,
    defaultMainIcon: '../../icons/elm1.png',
    platform: 2
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    text({
      type: 4
    }).then(res => {
      this.setData({
        attentions: res.data
      })
    })

    text({
      type: 6
    }).then(res => {
      this.setData({
        notices: res.data
      })
    })
    this.listActivities()
  },


  /**
   * 跳转到小程序
   * @param {*} e 
   */
  navigateToMiniProgram(e) {
    this.getPromotion(e.currentTarget.dataset.actid).then(res => {
      wx.navigateToMiniProgram({
        appId: res.appId,
        path: res.pagePath,
        success: res => {
          cilckRecord({
            clickType: e.currentTarget.dataset.actid
          })
        }
      })
    })
  },
  /**
   * 查询美团平台活动信息
   */
  listActivities() {
    listActivities({
      platform: this.data.platform
    }).then(res => {
      if (res.data) {
        const mainActs = res.data.filter(item => {
          if (item.mainAct === 1) {
            return item
          }
        })
        const acts = res.data.filter(item => {
          if (item.mainAct === 0) {
            return item
          }
        })
        const images = res.data.map(item => {
          return item.image
        })
        this.setData({
          mainActs: mainActs,
          acts: acts,
          images: images
        })
        for (let index = 0; index < this.data.mainActs.length; index++) {
          const act = this.data.mainActs[index]
          this.getPromotion(act.actId).then(res => {
            this.setData({
              ['mainActs[' + index + '].miniCode']: res.miniCode
            })
          })
        }
      }
      this.setData({
        loading: false
      })
    })
  },
  /**
   * 查询活动信息
   */
  getPromotion(actId) {
    wx.showLoading({
      title: '加载中',
    })
    return new Promise((resolve, reject) => {
      getPromotion({
        platform: this.data.platform,
        actId: actId
      }).then(res => {
        wx.hideLoading({})
        resolve(res.data)
      })
    })
  }
})